package dao

import (
	"fmt"
	"gin-web/config"
	_ "github.com/go-sql-driver/mysql"
	"github.com/ngaut/log"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	systemlog "log"
	"os"
	"time"
)

var db *gorm.DB

//创建orm引擎
func DbInit() bool {
	var err error

	dbInfo := config.Cfg.Db
	host := dbInfo.Host
	port := dbInfo.Port
	user := dbInfo.Username
	pwd := dbInfo.Password
	database := dbInfo.Db

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, pwd, host, port, database)
	log.Infof("connect db %s\n", dsn)

	var gormLogger logger.Interface
	if dbInfo.LogPath != "" {
		path := fmt.Sprintf("%s%s-%s.log", dbInfo.LogPath,"/sql", time.Now().Format("2006-01-02"))
		f, _ := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
		gormLogger = logger.New(systemlog.New(f, "", log.LstdFlags), logger.Config{
			SlowThreshold: 200 * time.Millisecond,
			LogLevel: logger.Info,
		})
	}
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 如果设置禁用表名复数形式属性为 true，`User` 的表名将是 `user`
		}, // select * from xxx => select a,b,c from xxx
		QueryFields: true,
		Logger: gormLogger,
	})
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}
	//defer db.Close()

	if err != nil {
		log.Fatal("数据库连接失败:", err)
		return false
	}

	//runtime.SetFinalizer(a, finalizer)
	log.Info("db connect success")

	return true
}

func DB() *gorm.DB {
	return db
}
